import { NextResponse, type NextRequest } from 'next/server';
import type { GetObjectCommandInput } from '@aws-sdk/client-s3';
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { db } from '@/server/db/db';
import sharp from 'sharp';
import { getUserServerSession } from '@/server/auth';
import { TRPCError } from '@trpc/server';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const session = await getUserServerSession();
  if (!session?.user) {
    return new NextResponse('Unauthorized', { status: 401 });
  }

  const file = await db.query.files.findFirst({
    where: (files, { eq, and }) =>
      and(eq(files.id, id), eq(files.userId, session.user.id)),
    with: {
      app: {
        with: {
          storage: true,
        },
      },
    },
  });

  if (!file?.path || !file.contentType.startsWith('image')) {
    return new NextResponse('', {
      status: 400,
    });
  }

  if (!file.app?.storage?.configuration) {
    throw new TRPCError({
      code: 'BAD_REQUEST',
    });
  }

  const config = file.app.storage.configuration;

  const s3Client = new S3Client({
    endpoint: config.apiEndpoint,
    region: config.region,
    credentials: {
      accessKeyId: config.accessKeyId,
      secretAccessKey: config.secretAccessKey,
    },
  });

  const commandParams: GetObjectCommandInput = {
    Bucket: config.bucket,
    Key: file.path,
  };

  const command = new GetObjectCommand(commandParams);

  const response = await s3Client.send(command);

  const byteArray = await response.Body?.transformToByteArray();

  if (!byteArray) {
    return new NextResponse('', {
      status: 400,
    });
  }

  const image = sharp(byteArray);

  image.resize({
    width: 250,
    height: 250,
  });

  const buffer = await image.webp().toBuffer();

  return new NextResponse(buffer, {
    headers: {
      'Content-Type': 'image/webp',
      'Cache-Control': 'public, max-age=31536000, immutable',
    },
  });
}
